package com.sna.snaapplication.service.File.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sna.snaapplication.entity.File.FileEntity;
import com.sna.snaapplication.entity.File.FileInfoDTO;
import com.sna.snaapplication.mapper.FileHistoryMapper;
import com.sna.snaapplication.mapper.FileMapper;
import com.sna.snaapplication.mapper.UserMapper;
import com.sna.snaapplication.service.File.FileService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    // 文件大小阈值(1MB)，超过此大小将存储在文件系统中
    private static final long LARGE_FILE_THRESHOLD = 1024 * 1024; // 1MB

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileHistoryMapper fileHistoryMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public void save(FileEntity file) {
        // 保存进文件库
        fileMapper.insert(file);
    }

    @Override
    public FileEntity getFileById(Long fileId) {
        return fileMapper.selectById(fileId);
    }

    @Override
    public List<FileInfoDTO> getUserFiles(Long userId) {
        // 查询用户的所有文件
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<FileEntity> fileEntities = fileMapper.selectList(queryWrapper);

        // 转换为DTO
        List<FileInfoDTO> result = new ArrayList<>();
        for (FileEntity file : fileEntities) {
            result.add(new FileInfoDTO(file.getId(), file.getName()));
        }

        return result;
    }

    @Override
    public boolean removeById(Long fileId) {
        try {
            int result = fileMapper.deleteById(fileId);
            logger.info("删除文件记录成功，文件ID: {}", fileId);
            return result > 0;
        } catch (Exception e) {
            logger.error("删除文件记录失败，文件ID: {}, 错误: {}", fileId, e.getMessage());
            return false;
        }
    }

    @Override
    public FileEntity getFileByNameAndUserId(String fileName, Long userId) {
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", fileName)
                .eq("user_id", userId);
        return fileMapper.selectOne(queryWrapper);
    }
}
